<template>
  <div class="app-container" :key="`${operationType}-${articleId || 'new'}`">
    <div slot="header" class="clearfix">
      <span class="card-title">{{ title }}</span>
      <div class="card-actions">
        <el-button @click="goBack" icon="el-icon-back">返回</el-button>
      </div>
    </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <enhanced-editor v-model="form.title" :min-height="120" :max-height="200" placeholder="请输入内容"/>
        </el-form-item>

        <!-- 副标题部分 -->
        <el-form-item label="副标题">
          <div v-for="(subtitle, index) in subtitles" :key="index" class="subtitle-item">
            <enhanced-editor v-model="form[`littleTitle${index + 1}`]" :placeholder="`请输入副标题${index + 1}`" :min-height="120" :max-height="200" />
          </div>
          <el-button
            v-if="subtitles.length < 2"
            type="text"
            icon="el-icon-plus"
            @click="addSubtitle"
          >
            添加副标题
          </el-button>
        </el-form-item>

        <el-form-item label="文章来源" prop="articleOrigin">
          <el-autocomplete
            v-model="form.articleOrigin"
            :fetch-suggestions="querySearchSource"
            placeholder="请输入文章来源"
            clearable
            style="width: 223px;"
          />
        </el-form-item>

        <el-form-item label="栏目名称" prop="name">
          <el-select v-model="form.name" placeholder="请选择栏目名称"
            clearable
            filterable
            @change="handleColumnChange"
            :key="selectKey"
          >
            <el-option
              v-for="item in columnOptions"
              :key="item.columnId"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>

        <el-form-item label="责任编辑" prop="author">
          <el-autocomplete
            v-model="form.author"
            :fetch-suggestions="querySearchAuthor"
            placeholder="请输入责任编辑"
            clearable
            style="width: 223px;"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>

        <!-- 封面路径 - 只有媒体聚焦栏目才显示 -->
        <el-form-item label="封面路径" prop="coverPath" v-if="isMediaFocusColumn">
          <el-upload
            ref="upload"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :auto-upload="false"
            :on-remove="handleRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传封面图片，大小不小于1MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="审批表" prop="appval">
          <el-upload
            ref="appvalUpload"
            :file-list="appvalFileList"
            :before-upload="beforeAppvalUpload"
            :on-change="handleAppvalFileChange"
            :auto-upload="false"
            :on-remove="handleAppvalRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleAppvalHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传审批表图片</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="附件" prop="attachment">
          <el-upload
            ref="attachmentUpload"
            :file-list="attachmentFileList"
            :before-upload="beforeAttachmentUpload"
            :on-change="handleAttachmentFileChange"
            :auto-upload="false"
            :on-remove="handleAttachmentRemove"
            :limit="1"
            list-type="text"
            action="#"
            :http-request="handleAttachmentHttpRequest"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <el-button
              v-if="form.attachment || temporaryAttachmentUrl"
              size="small"
              type="success"
              icon="el-icon-download"
              @click.stop="downloadAttachment(form.attachment || temporaryAttachmentUrl, getAttachmentFileName(form.attachment || temporaryAttachmentUrl))"
              style="margin-left: 10px;"
            >
              下载附件
            </el-button>
            <div slot="tip" class="el-upload__tip">请上传附件文件</div>
          </el-upload>
        </el-form-item>

        <!-- PDF转图片预览区域 -->
        <el-form-item v-if="pdfImagePaths && pdfImagePaths.length > 0" label="PDF预览">
          <div class="pdf-preview-container">
            <div
              v-for="(imagePath, index) in pdfImagePaths"
              :key="index"
              class="pdf-page-preview"
            >
              <img
                :src="imagePath"
                :alt="`PDF第${index + 1}页`"
                class="pdf-page-image"
                @click="previewPdfImage(imagePath, index)"
              />
              <div class="pdf-page-number">第{{ index + 1 }}页</div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div class="form-footer">
        <!-- 编辑草稿时显示更新草稿、直接发布、取消按钮 -->
        <template v-if="title === '修改草稿'">
          <el-button type="primary" @click="handleUpdateDraft">更新草稿</el-button>
          <el-button type="success" class="draft-publish-button" @click="handlePublishFromDraft">直接发布</el-button>
          <el-button @click="goBack">取消</el-button>
        </template>
        <!-- 编辑正式文章时显示确定、保存草稿、取消按钮 -->
        <template v-else>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button type="warning" class="draft-save-button" @click="handleSaveDraft">保存草稿</el-button>
          <el-button @click="goBack">取 消</el-button>
        </template>
      </div>

    <!-- 封面图片选择对话框 -->
    <el-dialog :visible.sync="coverDialogVisible" title="选择或上传封面图片" width="800px">
      <el-row :gutter="20">
        <!-- 从文章内容中选择图片 -->
        <el-col :span="12">
          <div class="cover-section-title">从文章中选择</div>
          <div v-if="articleImages.length > 0" class="image-list">
            <div
              v-for="(image, index) in articleImages"
              :key="index"
              class="image-item"
              :class="{ selected: selectedCoverImage === image }"
              @click="selectCoverImage(image)"
            >
              <img :src="image" alt="封面图片" class="cover-preview" />
            </div>
          </div>
          <div v-else class="no-image-tip">
            文章内容中没有图片，请手动上传封面。
          </div>
        </el-col>

        <!-- 手动上传图片 -->
        <el-col :span="12">
          <div class="cover-section-title">手动上传</div>
          <el-upload
            ref="manualCoverUpload"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :auto-upload="false"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleHttpRequest"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="el-upload__tip">请上传封面图片，大小不小于1MB</div>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="coverDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCoverSelection">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listConlumn, getConlumn, listConlumnList } from "@/api/conlumn/conlumn";
import { uploadFile, uploadAppval, uploadContentImage, uploadAttachment } from "@/api/article/article";
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/article/article";
import { addRiver_news, listRiver_news } from "@/api/river_news/river_news";
import { listToutiao, delToutiao, addToutiao } from "@/api/toutiao/toutiao";
import { hideArticle, showArticle, batchHideArticle, batchShowArticle, batchHideArticleByCondition, batchShowArticleByCondition } from "@/api/article/article";
import { saveDraft, updateDraft, publishDraft, listDraft } from "@/api/article/article";
import { delDraft, getDraft } from "@/api/draft/index";
import EnhancedEditor from "@/components/Editor/EnhancedEditor";
import Editor from "@/components/Editor";
import imageCompression from "browser-image-compression";

export default {
  name: "ArticleForm",
  dicts: ['status'],
  components: {
    EnhancedEditor,
    Editor
  },
  computed: {
    // 判断当前选择的栏目是否为媒体聚焦
    isMediaFocusColumn() {
      if (!this.form.columnId || !this.columnOptions.length) {
        return false;
      }
      const selectedColumn = this.columnOptions.find(col => col.id === this.form.columnId);
      return selectedColumn && selectedColumn.name === '媒体聚焦';
    }
  },
  data() {
    return {
      // 页面标题
      title: "",
      // 操作类型：add, edit, draft
      operationType: "",
      // 文章ID（编辑时使用）
      articleId: null,

      // 封面相关
      coverDialogVisible: false,
      coverSelectTab: 'select',
      articleImages: [],
      selectedCoverImage: null,

      // 副标题
      subtitles: [],

      // 文件上传相关
      appvalFileList: [],
      uploadAppvalFile: null,
      attachmentFileList: [],
      uploadAttachmentFile: null,
      temporaryAttachmentUrl: null,

      // 审批表状态管理
      appvalState: {
        currentUrl: null,
        pendingFile: null,
        isRemoved: false,
        originalUrl: null,
      },

      uploadRes: [],
      fileList: [],
      uploadFile: null,

      // 防止重复提交
      isSubmitting: false,

      // 栏目选项
      columnOptions: [],

      // 表单参数
      form: {},

      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "栏目名称不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ]
      },

      // 历史记录
      sourceHistory: [],
      authorHistory: [],
      selectKey: 0,

      // PDF预览
      pdfImagePaths: [],

      // 暂存文件（用于新增时）
      tempCoverFile: null,
      tempAppvalFile: null,
      tempAttachmentFile: null
    };
  },
  created() {
    this.initPage();
  },
  watch: {
    // 监听路由参数变化
    '$route.query': {
      handler(newQuery, oldQuery) {
        // 当路由参数变化时，重新初始化页面
        if (newQuery.operationType !== oldQuery.operationType || newQuery.id !== oldQuery.id) {
          this.initPage();
        }
      },
      deep: true,
      immediate: false
    },
    'form.title'(newVal) {
      this.checkLineLength();
    },
    'form.columnId'(newVal) {
      if (newVal && this.columnOptions.length > 0) {
        const column = this.columnOptions.find(item => item.id === newVal);
        this.form.name = column ? column.name : '';
      }
    },
    columnOptions: {
      handler(newVal) {
        if (newVal.length > 0 && this.form?.columnId) {
          const column = newVal.find(item => item.id === this.form.columnId);
          this.form.name = column ? column.name : '';
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 初始化页面
    initPage() {
      // 先清空所有数据状态
      this.reset();

      this.getColumnList();
      this.loadHistory();

      // 获取路由参数
      const { operationType, id } = this.$route.query;
      this.operationType = operationType || 'add';
      this.articleId = id ? parseInt(id) : null;

      // 设置页面标题
      this.setPageTitle();

      // 如果是编辑模式，加载数据
      if (this.operationType === 'edit' && this.articleId) {
        this.loadArticleData();
      } else if (this.operationType === 'draft' && this.articleId) {
        this.loadDraftData();
      }

      // 重新初始化表单
      this.$nextTick(() => {
        this.initForm();
      });
    },

    // 初始化表单
    initForm() {
      // 清空表单验证状态
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }

      // 清空文件上传组件的状态
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      if (this.$refs.appvalUpload) {
        this.$refs.appvalUpload.clearFiles();
      }
      if (this.$refs.attachmentUpload) {
        this.$refs.attachmentUpload.clearFiles();
      }

      // 确保表单包含必要的字段
      if (!this.form.hasOwnProperty('appval')) {
        this.$set(this.form, 'appval', null);
      }
      if (!this.form.hasOwnProperty('attachment')) {
        this.$set(this.form, 'attachment', null);
      }

      // 重置副标题状态
      this.subtitles = [];

      // 重置选择器key，强制重新渲染
      this.selectKey += 1;

      // 强制重新渲染表单组件
      this.$forceUpdate();
    },

    // 设置页面标题
    setPageTitle() {
      switch (this.operationType) {
        case 'add':
          this.title = '新增文章';
          break;
        case 'edit':
          this.title = '修改文章';
          break;
        case 'draft':
          this.title = '修改草稿';
          break;
        default:
          this.title = '文章管理';
      }
    },

    // 加载栏目列表
    getColumnList() {
      listConlumnList().then(response => {
        this.columnOptions = response.rows || [];
      });
    },

    // 加载历史记录
    loadHistory() {
      // 加载文章来源历史记录
      const storedHistory = localStorage.getItem('sourceHistory');
      if (storedHistory) {
        const historyData = JSON.parse(storedHistory);
        const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);
        this.sourceHistory = historyData.filter(item => item.timestamp > thirtyDaysAgo)
          .map(item => item.value);
      }

      // 加载责任编辑历史记录
      const storedAuthorHistory = localStorage.getItem('authorHistory');
      if (storedAuthorHistory) {
        const authorHistoryData = JSON.parse(storedAuthorHistory);
        const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);
        this.authorHistory = authorHistoryData.filter(item => item.timestamp > thirtyDaysAgo)
          .map(item => item.value);
      }
    },

    // 加载文章数据
    loadArticleData() {
      getArticle(this.articleId).then(response => {
        this.form = response.data || response;
        this.initFileLists();
        this.extractImagesFromContent();
      });
    },

    // 加载草稿数据
    loadDraftData() {
      getDraft(this.articleId).then(response => {
        this.form = response.data || response;
        this.initFileLists();
        this.extractImagesFromContent();
      });
    },

    // 初始化文件列表
    initFileLists() {
      // 初始化封面文件列表
      if (this.form.coverPath) {
        this.fileList = [{
          name: "封面图片",
          url: this.form.coverPath
        }];
      } else {
        this.fileList = [];
      }

      // 初始化审批表文件列表
      if (this.form.appval) {
        this.appvalFileList = [{
          name: "审批表",
          url: this.form.appval
        }];
        this.appvalState.currentUrl = this.form.appval;
        this.appvalState.originalUrl = this.form.appval;
      } else {
        this.appvalFileList = [];
      }

      // 初始化附件文件列表
      if (this.form.attachment) {
        this.attachmentFileList = [{
          name: this.getAttachmentFileName(this.form.attachment),
          url: this.form.attachment
        }];
        this.temporaryAttachmentUrl = this.form.attachment;
      } else {
        this.attachmentFileList = [];
      }
    },

    // 从文章内容中提取图片
    extractImagesFromContent() {
      if (this.form.content) {
        this.articleImages = this.extractImagesFromContentString(this.form.content);
      }
    },

    // 重置表单
    reset() {
      this.form = {
        id: null,
        title: null,
        articleOrigin: null,
        columnId: null,
        name: null,
        content: null,
        author: null,
        remark: null,
        coverPath: null,
        appval: null,
        attachment: null
      };
      this.subtitles = [];
      this.fileList = [];
      this.appvalFileList = [];
      this.attachmentFileList = [];
      this.uploadFile = null;
      this.uploadAppvalFile = null;
      this.uploadAttachmentFile = null;
      this.temporaryAttachmentUrl = null;
      this.articleImages = [];
      this.selectedCoverImage = null;
      this.pdfImagePaths = [];

      // 清空暂存文件
      this.tempCoverFile = null;
      this.tempAppvalFile = null;
      this.tempAttachmentFile = null;

      this.resetForm("form");
    },

    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },

    // 添加副标题
    addSubtitle() {
      if (this.subtitles.length < 2) {
        this.subtitles.push(`littleTitle${this.subtitles.length + 1}`);
      }
    },

    // 栏目变化处理
    handleColumnChange(value) {
      if (value && this.columnOptions.length > 0) {
        const column = this.columnOptions.find(item => item.name === value);
        if (column) {
          this.form.columnId = column.id;
        }
      }
    },

    // 文章来源搜索建议
    querySearchSource(queryString, cb) {
      const suggestions = this.sourceHistory.filter(item =>
        item.toLowerCase().includes(queryString.toLowerCase())
      );
      cb(suggestions.map(item => ({ value: item })));
    },

    // 责任编辑搜索建议
    querySearchAuthor(queryString, cb) {
      const suggestions = this.authorHistory.filter(item =>
        item.toLowerCase().includes(queryString.toLowerCase())
      );
      cb(suggestions.map(item => ({ value: item })));
    },

    // 检查行长度
    checkLineLength() {
      if (this.form.title) {
        const lines = this.form.title.split('\n');
        const maxLength = 20;
        const longLines = lines.filter(line => line.length > maxLength);
        if (longLines.length > 0) {
          this.showLineLengthWarning = `标题第${lines.indexOf(longLines[0]) + 1}行超过${maxLength}个字符`;
        } else {
          this.showLineLengthWarning = '';
        }
      }
    },

    // 提交表单
    async submitForm() {
      if (this.isSubmitting) return;

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.isSubmitting = true;

          if (this.operationType === 'add') {
            this.handleAdd();
          } else if (this.operationType === 'edit') {
            this.handleUpdate();
          }
        }
      });
    },

    // 新增文章
    async handleAdd() {
      try {
        // 保存历史记录
        this.saveHistory();

        // 准备提交的表单数据，确保包含 appval 和 attachment
        const formData = {
          ...this.form,
          appval: this.form.appval || this.appvalFileList[0].url,
          attachment: this.form.attachment || this.attachmentFileList[0].url
        };

        // 先提交表单，获取文章ID
        const response = await addArticle(this.form.title, formData);
        if (response.code === 200) {
          // 获取新创建的文章ID
          const newArticleId = response.data?.id || response.data?.articleId;

          // 如果有暂存的封面图片，现在上传
          if (this.tempCoverFile && newArticleId) {
            try {
              await this.uploadCoverAfterCreate(newArticleId);
            } catch (uploadError) {
              console.warn('封面上传失败，但文章已创建成功:', uploadError);
              this.$message.warning('文章创建成功，但封面上传失败，请稍后手动上传');
            }
          }

          // 如果有暂存的审批表图片，现在上传
          if (this.tempAppvalFile && newArticleId) {
            try {
              await this.uploadAppvalAfterCreate(newArticleId);
            } catch (uploadError) {
              console.warn('审批表上传失败，但文章已创建成功:', uploadError);
              this.$message.warning('文章创建成功，但审批表上传失败，请稍后手动上传');
            }
          }

          // 如果有暂存的附件，现在上传
          if (this.tempAttachmentFile && newArticleId) {
            try {
              await this.uploadAttachmentAfterCreate(newArticleId);
            } catch (uploadError) {
              console.warn('附件上传失败，但文章已创建成功:', uploadError);
              this.$message.warning('文章创建成功，但附件上传失败，请稍后手动上传');
            }
          }

          this.$modal.msgSuccess("新增成功");
          // 清空表单数据状态
          this.reset();
          this.goBack();
        } else {
          this.$modal.msgError(response.msg || "新增失败");
        }
      } catch (error) {
        console.error('新增文章失败:', error);
        this.$modal.msgError('新增失败: ' + (error.message || '未知错误'));
      } finally {
        this.isSubmitting = false;
      }
    },

    // 修改文章
    async handleUpdate() {
      try {
        // 处理文件上传
        await this.handleFileUploads();

        // 保存历史记录
        this.saveHistory();

        // 准备提交的表单数据，确保包含 appval 和 attachment
        const formData = {
          ...this.form,
          appval: this.form.appval || this.appvalFileList[0].url,
          attachment: this.form.attachment || this.attachmentFileList[0].url
        };

        const response = await updateArticle(formData);
        if (response.code === 200) {
          this.$modal.msgSuccess("修改成功");
          this.goBack();
        } else {
          this.$modal.msgError(response.msg || "修改失败");
        }
      } catch (error) {
        console.error('修改文章失败:', error);
        this.$modal.msgError('修改失败: ' + (error.message || '未知错误'));
      } finally {
        this.isSubmitting = false;
      }
    },

    // 保存草稿
    async handleSaveDraft() {
      if (this.isSubmitting) return;

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.isSubmitting = true;
          this.saveDraft();
        }
      });
    },

    // 保存草稿到服务器
    async saveDraft() {
      try {
        // 处理文件上传
        await this.handleFileUploads();

        // 保存历史记录
        this.saveHistory();

        // 准备提交的表单数据，确保包含 appval 和 attachment
        const formData = {
          ...this.form,
          appval: this.form.appval || this.appvalFileList[0].url,
          attachment: this.form.attachment || this.attachmentFileList[0].url
        };

        const response = await saveDraft(formData);
        if (response.code === 200) {
          this.$modal.msgSuccess("草稿保存成功");
          // 清空表单数据状态
          this.reset();
          this.goBack();
        } else {
          this.$modal.msgError(response.msg || "草稿保存失败");
        }
      } catch (error) {
        console.error('保存草稿失败:', error);
        this.$modal.msgError('保存草稿失败: ' + (error.message || '未知错误'));
      } finally {
        this.isSubmitting = false;
      }
    },

    // 更新草稿
    async handleUpdateDraft() {
      if (this.isSubmitting) return;

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.isSubmitting = true;
          this.updateDraft();
        }
      });
    },

    // 更新草稿到服务器
    async updateDraft() {
      try {
        // 处理文件上传
        await this.handleFileUploads();

        // 保存历史记录
        this.saveHistory();

        // 准备提交的表单数据，确保包含 appval 和 attachment
        const formData = {
          ...this.form,
          appval: this.form.appval || null,
          attachment: this.form.attachment || null
        };

        const response = await updateDraft(formData);
        if (response.code === 200) {
          this.$modal.msgSuccess("草稿更新成功");
          this.goBack();
        } else {
          this.$modal.msgError(response.msg || "草稿更新失败");
        }
      } catch (error) {
        console.error('更新草稿失败:', error);
        this.$modal.msgError('更新草稿失败: ' + (error.message || '未知错误'));
      } finally {
        this.isSubmitting = false;
      }
    },

    // 从草稿直接发布
    async handlePublishFromDraft() {
      if (this.isSubmitting) return;

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.isSubmitting = true;
          this.publishFromDraft();
        }
      });
    },

    // 从草稿发布
    async publishFromDraft() {
      try {
        // 处理文件上传
        await this.handleFileUploads();

        // 保存历史记录
        this.saveHistory();

        // 准备提交的表单数据，确保包含 appval 和 attachment
        const formData = {
          ...this.form,
          appval: this.form.appval || null,
          attachment: this.form.attachment || null
        };

        const response = await publishDraft(formData);
        if (response.code === 200) {
          this.$modal.msgSuccess("发布成功");
          this.goBack();
        } else {
          this.$modal.msgError(response.msg || "发布失败");
        }
      } catch (error) {
        console.error('发布失败:', error);
        this.$modal.msgError('发布失败: ' + (error.message || '未知错误'));
      } finally {
        this.isSubmitting = false;
      }
    },

    // 处理文件上传
    async handleFileUploads() {
      // 处理封面图片上传
      if (this.uploadFile) {
        await this.uploadFileToServer(this.uploadFile);
      }

      // 处理审批表上传
      if (this.uploadAppvalFile) {
        await this.uploadAppvalToServer(this.uploadAppvalFile);
      }

      // 处理附件上传
      if (this.uploadAttachmentFile) {
        await this.uploadAttachmentToServer(this.uploadAttachmentFile);
      }
    },

    // 保存历史记录
    saveHistory() {
      // 保存文章来源历史记录
      if (this.form.articleOrigin && this.form.articleOrigin.trim()) {
        this.addToHistory('sourceHistory', this.form.articleOrigin.trim());
      }

      // 保存责任编辑历史记录
      if (this.form.author && this.form.author.trim()) {
        this.addToHistory('authorHistory', this.form.author.trim());
      }
    },

    // 添加到历史记录
    addToHistory(key, value) {
      const history = JSON.parse(localStorage.getItem(key) || '[]');
      const now = Date.now();

      // 移除重复项
      const filteredHistory = history.filter(item => item.value !== value);

      // 添加新项到开头
      filteredHistory.unshift({ value, timestamp: now });

      // 只保留最近10条记录
      const limitedHistory = filteredHistory.slice(0, 10);

      localStorage.setItem(key, JSON.stringify(limitedHistory));
    },

    // 文件上传相关方法（从原页面复制）
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }

      // 如果是新增模式，暂存文件
      if (this.operationType === 'add') {
        this.tempCoverFile = file;
        this.$message.info('封面图片已选择，将在文章创建后上传');
      } else {
        this.uploadFile = file;
      }
      return false;
    },

    handleFileChange(file, fileList) {
      if (fileList.length > 0) {
        this.uploadFile = fileList[fileList.length - 1].raw;
        this.fileList = [fileList[fileList.length - 1]];
      } else {
        this.uploadFile = null;
        this.fileList = [];
      }
    },

    handleRemove(file, fileList) {
      this.uploadFile = null;
      this.fileList = [];
    },

    async uploadFileToServer(file) {
      if (!file) return;

      try {
        const compressedFile = await this.compressImage(file);
        const formData = new FormData();
        formData.append('file', compressedFile);

        const response = await uploadFile(formData);
        if (response.code === 200) {
          this.form.coverPath = response.url;
        }
      } catch (error) {
        console.error('封面图片上传失败:', error);
        throw error;
      }
    },

    // 图片压缩方法（从原页面复制）
    async compressImage(file, checkMinSize = true) {
      const minSizeBytes = 1024 * 1024; // 1MB 下限
      const maxSizeBytes = 5 * 1024 * 1024; // 5MB 上限
      const skipCompressSizeBytes = 3 * 1024 * 1024; // 3MB

      if (checkMinSize && file.size < minSizeBytes) {
        throw new Error('封面大小不能小于1MB!');
      }

      if (file.size < skipCompressSizeBytes) {
        return file;
      }

      return await this.canvasCompress(file, minSizeBytes, maxSizeBytes);
    },

    // Canvas压缩方法（从原页面复制）
    async canvasCompress(file, minSizeBytes, maxSizeBytes) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();

        img.onload = async () => {
          let width = img.width;
          let height = img.height;
          const ratio = width / height;

          if (width > 2048 || height > 2048) {
            if (width > height) {
              width = 2048;
              height = 2048 / ratio;
            } else {
              height = 2048;
              width = 2048 * ratio;
            }
          }

          canvas.width = width;
          canvas.height = height;
          ctx.drawImage(img, 0, 0, width, height);

          let quality = 1;
          let minQuality = 0.1;
          let maxQuality = 2;
          let attempts = 0;
          const maxAttempts = 10;

          let compressedBlob;

          while (attempts < maxAttempts) {
            attempts++;
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', quality);
            });

            if (compressedBlob.size >= minSizeBytes && compressedBlob.size <= maxSizeBytes) {
              break;
            }

            if (compressedBlob.size > maxSizeBytes) {
              maxQuality = quality;
              quality = (minQuality + quality) / 2;
            } else {
              minQuality = quality;
              quality = (quality + maxQuality) / 2;
            }

            if (quality < 0.01) {
              break;
            }
          }

          if (compressedBlob.size < minSizeBytes) {
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', 0.95);
            });
          }

          const compressedFile = new File([compressedBlob], file.name, {
            type: 'image/jpeg',
            lastModified: Date.now()
          });

          resolve(compressedFile);
        };

        img.onerror = () => {
          reject(new Error('图片加载失败'));
        };

        const reader = new FileReader();
        reader.onload = e => {
          img.src = e.target.result;
        };
        reader.onerror = () => {
          reject(new Error('文件读取失败'));
        };
        reader.readAsDataURL(file);
      });
    },

    // 审批表上传相关方法
    beforeAppvalUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }

      // 如果是新增模式，暂存文件
      if (this.operationType === 'add') {
        this.tempAppvalFile = file;
        // this.$message.info('审批表已选择，将在文章创建后上传');
      } else {
        this.uploadAppvalFile = file;
      }
      return false;
    },

    handleAppvalFileChange(file, fileList) {
      if (fileList.length > 0) {
        this.uploadAppvalFile = fileList[fileList.length - 1].raw;
        this.appvalFileList = [fileList[fileList.length - 1]];
        this.appvalState.pendingFile = fileList[0].raw;
        this.appvalState.isRemoved = false;
        this.appvalState.currentUrl = null;
        this.appvalState.originalUrl = null;
      } else {
        this.uploadAppvalFile = null;
        this.appvalFileList = [];
        this.appvalState.isRemoved = true;
        this.form.appval = null;
        this.appvalState.pendingFile = null;
        this.appvalState.currentUrl = null;
        this.appvalState.originalUrl = null;
      }
    },

    handleAppvalRemove(file, fileList) {
      this.uploadAppvalFile = null;
      this.appvalFileList = [];
      this.appvalState.isRemoved = true;
      this.form.appval = null;
    },

    handleAppvalHttpRequest(options) {
      this.uploadAppvalToServer(options.file);
    },

    async uploadAppvalToServer(file) {
      if (!file || !(file instanceof File)) {
        console.error('无效的文件对象:', file);
        this.$message.error('审批表文件无效');
        return;
      }

      const formData = new FormData();
      formData.append('appvalPath', file);

      try {
        const response = await uploadAppval(this.form.articleId || 0, formData);
        if (response.code === 200) {
          this.form.appval = response.url;
          this.appvalState.currentUrl = response.url;
          this.appvalState.originalUrl = response.url;
          this.appvalState.isRemoved = false;
          this.appvalState.pendingFile = null;
          this.$message.success('审批表上传成功');
          return response;
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('审批表上传失败:', error);
        this.$message.error('审批表上传失败: ' + error.message);
        throw error;
      }
    },

    // 附件上传相关方法
    beforeAttachmentUpload(file) {
      // 如果是新增模式，暂存文件
      if (this.operationType === 'add') {
        this.tempAttachmentFile = file;
        this.$message.info('附件已选择，将在文章创建后上传');
      } else {
        this.uploadAttachmentFile = file;
      }
      return false;
    },

    handleAttachmentFileChange(file, fileList) {
      if (fileList.length > 0) {
        this.uploadAttachmentFile = fileList[fileList.length - 1].raw;
        this.attachmentFileList = [fileList[fileList.length - 1]];
      } else {
        this.uploadAttachmentFile = null;
        this.attachmentFileList = [];
      }
    },

    handleAttachmentRemove(file, fileList) {
      this.uploadAttachmentFile = null;
      this.attachmentFileList = [];
      this.temporaryAttachmentUrl = null;
    },

    handleAttachmentHttpRequest(options) {
      this.uploadAttachmentToServer(options.file);
    },

    async uploadAttachmentToServer(file) {
      if (!file || !(file instanceof File)) {
        console.error('无效的文件对象:', file);
        this.$message.error('附件文件无效');
        return;
      }

      const formData = new FormData();
      formData.append('attachment', file);

      try {
        const response = await uploadAttachment(formData);
        if (response.code === 200) {
          this.form.attachment = response.url;
          this.temporaryAttachmentUrl = response.url;
          this.$message.success('附件上传成功');
          return response;
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('附件上传失败:', error);
        this.$message.error('附件上传失败: ' + error.message);
        throw error;
      }
    },

    // 下载附件
    downloadAttachment(url, filename) {
      if (!url) {
        this.$message.error('附件URL不存在');
        return;
      }

      const link = document.createElement('a');
      link.href = url;
      link.download = filename || '附件';
      link.target = '_blank';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // 获取附件文件名
    getAttachmentFileName(url) {
      if (!url) return '附件';
      const parts = url.split('/');
      return parts[parts.length - 1] || '附件';
    },

    // 从文章内容中提取图片URL
    extractImagesFromContentString(content) {
      if (!content) return [];
      const imgRegex = /<img[^>]+src="([^">]+)"/g;
      const matches = content.match(imgRegex);
      if (!matches) return [];

      return matches.map(match => {
        const srcMatch = match.match(/src="([^">]+)"/);
        return srcMatch ? srcMatch[1] : null;
      }).filter(src => src);
    },

    // 选择封面图片
    selectCoverImage(image) {
      this.selectedCoverImage = image;
    },

    // 确认封面选择
    confirmCoverSelection() {
      if (this.selectedCoverImage) {
        this.coverDialogVisible = false;
        this.uploadCoverImage(this.selectedCoverImage);
      } else if (this.uploadFile) {
        this.coverDialogVisible = false;
        if (this.uploadFile.url) {
          this.form.coverPath = this.uploadFile.url;
          this.$message.success('封面图片设置成功');
        } else {
          this.compressImage(this.uploadFile).then(compressedFile => {
            this.uploadFile = compressedFile;
            this.uploadFileToServer(this.uploadFile);
          }).catch(error => {
            console.error('压缩图片失败:', error);
            this.$message.error('压缩图片失败: ' + error.message);
          });
        }
      } else {
        this.$modal.msgError("请选择或上传封面图片！");
      }
    },

    // 上传封面图片
    async uploadCoverImage(imageUrl) {
      try {
        const response = await fetch(imageUrl);
        const blob = await response.blob();
        const file = new File([blob], 'cover.jpg', { type: 'image/jpeg' });

        await this.compressImage(file).then(compressedFile => {
          this.uploadFile = compressedFile;
          this.uploadFileToServer(this.uploadFile);
        });
      } catch (error) {
        console.error('上传封面图片失败:', error);
        this.$message.error('上传封面图片失败: ' + error.message);
      }
    },

    // 预览PDF图片
    previewPdfImage(imagePath, index) {
      // 实现PDF图片预览逻辑
      console.log('预览PDF图片:', imagePath, index);
    },

    // 新增后上传封面图片
    async uploadCoverAfterCreate(articleId) {
      if (!this.tempCoverFile) return;

      try {
        const compressedFile = await this.compressImage(this.tempCoverFile);
        const formData = new FormData();
        formData.append('file', compressedFile);

        const response = await uploadFile(formData);
        if (response.code === 200) {
          // 更新文章的封面路径
          await updateArticle({
            id: articleId,
            coverPath: response.url
          });
          this.$message.success('封面上传成功');
        }
      } catch (error) {
        console.error('新增后封面上传失败:', error);
        throw error;
      }
    },

    // 新增后上传审批表
    async uploadAppvalAfterCreate(articleId) {
      if (!this.tempAppvalFile) return;

      try {
        const formData = new FormData();
        formData.append('appvalPath', this.tempAppvalFile);

        const response = await uploadAppval(articleId, formData);
        if (response.code === 200) {
          this.$message.success('审批表上传成功');
        }
      } catch (error) {
        console.error('新增后审批表上传失败:', error);
        throw error;
      }
    },

    // 新增后上传附件
    async uploadAttachmentAfterCreate(articleId) {
      if (!this.tempAttachmentFile) return;

      try {
        const formData = new FormData();
        formData.append('attachment', this.tempAttachmentFile);

        const response = await uploadAttachment(formData);
        if (response.code === 200) {
          // 更新文章的附件路径
          await updateArticle({
            id: articleId,
            attachment: response.url
          });
          this.$message.success('附件上传成功');
        }
      } catch (error) {
        console.error('新增后附件上传失败:', error);
        throw error;
      }
    },

    // 实现缺失的 handleHttpRequest 方法（封面图片上传）
    handleHttpRequest(options) {
      this.uploadFileToServer(options.file);
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.card-actions {
  float: right;
}

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

.form-footer {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

.subtitle-item {
  margin-bottom: 10px;
}

.pdf-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pdf-page-preview {
  position: relative;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.pdf-page-image {
  width: 100px;
  height: 140px;
  object-fit: cover;
  cursor: pointer;
}

.pdf-page-number {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  text-align: center;
  font-size: 12px;
  padding: 2px;
}

.cover-section-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.image-item {
  width: 80px;
  height: 80px;
  border: 2px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.3s;
}

.image-item:hover {
  border-color: #409eff;
}

.image-item.selected {
  border-color: #409eff;
}

.cover-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image-tip {
  color: #999;
  text-align: center;
  padding: 20px;
}
</style>
